package com.my.doc;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.my.EsClient;
import com.my.entity.Person;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.junit.Test;

import java.io.IOException;
import java.util.Date;

public class Bluk {
    //json转换⼯具对象
    private ObjectMapper mapper = new ObjectMapper();
    //es连接
    private RestHighLevelClient client = EsClient.getClient();
    //索引名字
    private String index = "person";


    /**
     * 批量添加数据
     * @throws IOException
     */
    @Test
    public void testBulkCreateDoc() throws IOException {
        //1. 准备多个person实体数据
        Person p1 = new Person("1", "张三", 23, new Date());
        Person p2 = new Person("2", "李四", 24, new Date());
        Person p3 = new Person("3", "王五", 25, new Date());
        //2. 将实体数据转换成json格式
        String json1 = mapper.writeValueAsString(p1);
        String json2 = mapper.writeValueAsString(p2);
        String json3 = mapper.writeValueAsString(p3);
        //3. 创建批量执⾏请求对象，将准备好的数据封装进去
        BulkRequest request = new BulkRequest();
        request.add(new IndexRequest(index).id(p1.getId()).source(json1, XContentType.JSON));
        request.add(new IndexRequest(index).id(p2.getId()).source(json2, XContentType.JSON));
        request.add(new IndexRequest(index).id(p3.getId()).source(json3, XContentType.JSON));
        //3. ⽤client执⾏
        BulkResponse resp = client.bulk(request,
                RequestOptions.DEFAULT);
        //4. 输出结果
        System.out.println(resp.toString());
    }


    /**
     * 批量删除⽂档数据
     * @throws IOException
     */
    @Test
    public void bulkDeleteDoc() throws IOException {
        //1. 封装Request对象
        BulkRequest request = new BulkRequest();
        request.add(new DeleteRequest(index,"1"));
        request.add(new DeleteRequest(index,"2"));
        request.add(new DeleteRequest(index,"3"));
        //2. client执⾏
        BulkResponse resp = client.bulk(request, RequestOptions.DEFAULT);
        //3. 输出
        System.out.println(resp);
    }

}
